#include "AT24C02.h"

/**
 * @brief 从24c02内部地址读数据
 * @param ReadAddr:(0x00~0xFF)
 */
uint8_t AT24C02_ReadByte(uint8_t ReadAddr)
{
    uint8_t result;
    SimulateI2C_Start();
    SimulateI2C_SendByte(AT24C02_ADDRESS);
    SimulateI2C_ReceiveAck();
    SimulateI2C_SendByte(ReadAddr);
    SimulateI2C_ReceiveAck();
    SimulateI2C_Start();
    SimulateI2C_SendByte(AT24C02_ADDRESS | 0x01);
    SimulateI2C_ReceiveAck();
    result = SimulateI2C_ReceiveByte();
    SimulateI2C_SendAck(1);
    SimulateI2C_Stop();
    return result;
}

void AT24C02_ReadBuffer(uint8_t ReadAddr, uint8_t *pBuf, uint16_t len)
{
    uint8_t i;
    SimulateI2C_Start();
    SimulateI2C_SendByte(AT24C02_ADDRESS);
    SimulateI2C_ReceiveAck();
    SimulateI2C_SendByte(ReadAddr);
    SimulateI2C_ReceiveAck();
    SimulateI2C_Start();
    SimulateI2C_SendByte(AT24C02_ADDRESS | 0x01);
    SimulateI2C_ReceiveAck();
    for (i = 0; i < len; i++)
    {
        pBuf[i] = SimulateI2C_ReceiveByte();
        if (i == (len - 1))
        {
            SimulateI2C_SendAck(1);
        }
        else
        {
            SimulateI2C_SendAck(0);
        }
    }
    SimulateI2C_Stop();
}

/**
 * @brief 24C02容量:256byte
 * @param WriteAddr  0x00~0xFF
 * @param by    (如果保存字符):by=对应字符编码,例如by='A'
 */
void AT24C02_WriteByte(uint8_t WriteAddr, uint8_t by)
{
    SimulateI2C_Start();
    SimulateI2C_SendByte(AT24C02_ADDRESS);
    SimulateI2C_ReceiveAck();
    SimulateI2C_SendByte(WriteAddr);
    SimulateI2C_ReceiveAck();
    SimulateI2C_SendByte(by);
    SimulateI2C_ReceiveAck();
    SimulateI2C_Stop();
}

/**
 * @brief 24C02容量:(256byte); PageSize=16Byte;
 * @param WriteAddr  0x00~0xFF
 */
void AT24C02_WritePage(uint8_t WriteAddr, uint8_t *pBuf, uint16_t len)
{
    while (len > 0)
    {
        SimulateI2C_Start();
        SimulateI2C_SendByte(AT24C02_ADDRESS);
        SimulateI2C_ReceiveAck();
        SimulateI2C_SendByte(WriteAddr);
        SimulateI2C_ReceiveAck();
        while (len > 0)
        {
            SimulateI2C_SendByte(*pBuf);
            SimulateI2C_ReceiveAck();
            pBuf++;
            len--;
            if (((WriteAddr) % (AT24C02_PAGE_SIZE)) == ((AT24C02_PAGE_SIZE)-1)) // Page End
            {
                WriteAddr++;
                break;
            }
            WriteAddr++;
        }
        SimulateI2C_Stop();
        delay_ms(5);
    }
}
